package com.tool.ui;

import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import com.tool.BillType;
import com.tool.DataCenterPersistence;
import com.tool.DataCenterVO;
import com.tool.LicenseMgmt;
import com.tool.imp.ImportBase;
import com.tool.imp.ap.ApBillImp;
import com.tool.imp.ia.ProInBillImp;
import com.tool.imp.ia.PurInBillImp;

/**
 * 导入工具 基类
 * 
 * @author Evan.Hu
 * 
 */
public class ImportUtilUI extends AbstractImportUtilUI {

	private static final SimpleDateFormat Date_Format = new SimpleDateFormat("yyyy-MM-dd_HHmmss");
	/**
	 * 
	 */
	private static final long serialVersionUID = -1724943189655487047L;

	public ImportUtilUI() {
		super();
	}

	protected void onLoad() {
		super.onLoad();

		for (BillType billType : BillType.values()) {
			billTypeComboBox.addItem(billType);
		}

		loadDataCenter();

		logFileTxt.setText(System.getProperty("user.dir") + File.separator + "logs");
	}

	protected void dataCenter_ActionPerformed(ActionEvent e) {
		if (getWindow() instanceof JFrame) {
			new DialogUIHelper((JFrame) getWindow(), new DCListUI(), true).show();
		} else if (getWindow() instanceof JDialog) {
			new DialogUIHelper((JDialog) getWindow(), new DCListUI(), true).show();
		}

		loadDataCenter();
	}

	protected void licenseSet_ActionPerformed(ActionEvent e) {
		if (getWindow() instanceof JFrame) {
			new DialogUIHelper((JFrame) getWindow(), new LicenseUI(), true).show();
		} else if (getWindow() instanceof JDialog) {
			new DialogUIHelper((JDialog) getWindow(), new LicenseUI(), true).show();
		}

		btnImport.setEnabled(LicenseMgmt.isLicenseValid());
	}

	/**
	 * 源文件选择
	 */
	protected void srcFileSelect_ActionPerformed(ActionEvent e) {
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fc.setFileFilter(new FileFilter() {

			public boolean accept(File f) {
				if (f != null) {
					if (f.isDirectory()) {
						return true;
					}
					String tmp = f.getName().toLowerCase();
					if (tmp.endsWith(".xls") || tmp.endsWith(".xlsx") ) {
						return true;
					}
				}
				return false;
			}

			public String getDescription() {
				return resHelper.getString("excelFileFilterDescription");
			}
		});
		// fc.setFileFilter(new
		// FileNameExtensionFilter(getString("excelFileFilterDescription"),
		// "xls", "xlsx"));

		int result = fc.showOpenDialog(getWindow());
		if (result == JFileChooser.APPROVE_OPTION) {
			srcFileTxt.setText(fc.getSelectedFile().getPath());
		}
	}

	/**
	 * 日志文件存储目录选取
	 */
	protected void logFileSelect_ActionPerformed(ActionEvent e) {
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

		int result = fc.showOpenDialog(getWindow());
		if (result == JFileChooser.APPROVE_OPTION) {
			logFileTxt.setText(fc.getSelectedFile().getPath());
		}
	}

	/**
	 * 导入操作界面
	 */
	protected void import_ActionPerformed(ActionEvent e) {
		checkBeforeImport();
		StringBuffer infoBuffer = new StringBuffer();
		ImportBase impBase = null;
		String [] spFileTxt=srcFileTxt.getText().split("\\.");
		System.out.println("sp:::::"+spFileTxt);
		Boolean fileFlag=false;
		if(spFileTxt.length==2)
			
			//若是2003版本,则为true
			if(spFileTxt[1].equals("xls"))
				fileFlag=true;
				
		if (BillType.AP.equals(billTypeComboBox.getSelectedItem())) {
			impBase = new ApBillImp((DataCenterVO) dataCenterComboBox.getSelectedItem(), srcFileTxt.getText(),fileFlag);
		}
		else if (BillType.IA_CG.equals(billTypeComboBox.getSelectedItem())) {
			impBase = new PurInBillImp((DataCenterVO) dataCenterComboBox.getSelectedItem(), srcFileTxt.getText(),fileFlag);
		}
		else if (BillType.IA_CCP.equals(billTypeComboBox.getSelectedItem())) {
			impBase = new ProInBillImp((DataCenterVO) dataCenterComboBox.getSelectedItem(), srcFileTxt.getText(),fileFlag);
		}
		else {
			throw new RuntimeException("未处理的单据类型-" + billTypeComboBox.getSelectedItem());
		}
		impBase.excel2VO();
		impBase.setAndSaveVO();
		infoBuffer.append(impBase.getMessage());

		StringBuilder logFile = new StringBuilder(logFileTxt.getText());
		logFile.append(File.separator).append(billTypeComboBox.getSelectedItem()).append("-导入日志");
		logFile.append(Date_Format.format(new Date())).append(".txt");
		saveLog(logFile.toString(), infoBuffer.toString());
		JOptionPane.showMessageDialog(getWindow(), "完成导入,操作结果请查看日志", billTypeComboBox.getSelectedItem().toString() + "导入", JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * 导入操作前置检查
	 */
	protected void checkBeforeImport() {
		if (dataCenterComboBox.getSelectedItem() == null) {
			throw new RuntimeException("未选择数据中心");
		}
		if (srcFileTxt.getText() == null) {
			throw new RuntimeException("请选择要导入的Excel文件");
		}
		if (logFileTxt.getText() == null) {
			throw new RuntimeException("请选择日志文件生成目录");
		}
	}

	/**
	 * 保存操作日志
	 * 
	 * @param log
	 * @throws IOException
	 */
	protected void saveLog(String filePath, String log) {
		File logFile = new File(filePath);
		BufferedWriter bw = null;
		try {
			makeFile(logFile, false);
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
			bw.write(log);
			bw.flush();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(getWindow(), log, "生成日志文件错误", JOptionPane.ERROR_MESSAGE);
		} finally {
			if (bw != null)
				try {
					bw.close();
				} catch (IOException e) {
				}
		}

	}

	public void makeFile(File file, boolean isDerectory) throws IOException {
		if (!file.exists()) {
			if (!file.getParentFile().exists()) {
				makeFile(file.getParentFile(), true);
			}
			if (isDerectory) {
				file.mkdir();
			} else {
				file.createNewFile();
			}
		}

	}

	protected void about_ActionPerformed(ActionEvent e) {
	}

	/**
	 * 加载数据中心
	 */
	private void loadDataCenter() {
		dataCenterComboBox.removeAllItems();
		List<DataCenterVO> dclist = DataCenterPersistence.getDCList();
		for (DataCenterVO vo : dclist) {
			dataCenterComboBox.addItem(vo);
		}
	}

	public static void main(String[] args) {
		new ImportUtilUI().showUI();
	}

}
